package org.example.judge_comment.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import org.example.judge_comment.common.RequestAnnouncementParams;
import org.example.judge_comment.mapper.AnnouncementMapper;
import org.example.judge_comment.service.AnnounceService;
import org.example.judge_common.entity.PageResult;
import org.example.judge_common.entity.RequestParams;
import org.example.judge_common.util.IdWorker;
import org.example.judge_common.util.MyUtils;
import org.example.judge_pojo.Announcement;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.function.Consumer;


@Service("AnnouncementServiceImpl")
public class AnnouncementServiceImpl extends ServiceImpl<AnnouncementMapper, Announcement> implements AnnounceService {
    @Autowired
    private IdWorker idWorker;
    @Override
    public PageResult<Announcement> search(RequestAnnouncementParams params) {
        if(MyUtils.isEmpty(params.getField())){ //默认排序字段
            params.setField("create_time");
        }
        if(MyUtils.isEmpty(params.getOrder())){   //默认排序方式
            params.setOrder(RequestParams.DESC);
        }
        QueryWrapper<Announcement> queryWap = new QueryWrapper<>();
        //字段模糊匹配
        if(MyUtils.isNotEmpty(params.getKey())){
            queryWap.and(new Consumer<QueryWrapper<Announcement>>() { //隔离or条件
                @Override
                public void accept(QueryWrapper<Announcement> problemQueryWrapper) {
                    problemQueryWrapper.like("title",params.getKey()).or().like("text",params.getKey());
                }
            });

        }
        //比赛ID
//        if(params.getKey()!=null)queryWap.eq("contest_id",params.getKey());

        //权重
        queryWap.orderBy(true,false,"weight");
        //排序
        queryWap.orderBy(true,"asc".equalsIgnoreCase(params.getOrder()),params.getField());

        queryWap.eq(params.getStatus()!=null,"status",params.getStatus());
        //设置分页
        PageHelper.startPage(params.getPage(), params.getSize(),false);
        List<Announcement> problems = this.baseMapper.selectList(queryWap);
        //求数据条数
        Integer count = this.baseMapper.selectCount(queryWap);

        return new PageResult<Announcement>(count.longValue(),problems);
    }

    @Override
    public boolean save(Announcement entity) {
        entity.setId(idWorker.nextId().toString());
        entity.setCreateTime(new Date());
        return super.save(entity);
    }
}
